package itsm.isperp.module.controller.knowledge;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseProcessController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.knowledge.KngKnowledgeCategory;
import itsm.isperp.module.entity.knowledge.KngKnowledgeItem;
import itsm.isperp.module.service.knowledge.KngKnowledgeCategoryService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;
import itsm.isperp.module.utils.SolrUtils;
import itsm.isperp.workflow.service.BpmProcessRunService;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("knowledge/knowledgeItem")
public class KngKnowledgeItemController extends
		BaseProcessController<KngKnowledgeItem> {

	/**
	 * 
	 */
	@Autowired
	protected KngKnowledgeItemService kngKnowledgeItemService;

	@Override
	public KngKnowledgeItemService getService() {
		return kngKnowledgeItemService;
	}

	@Override
	public String getPageTitle() {
		return "知识";
	}

	@Override
	public String getProceessKey() {
		return "knowledgeProcess";
	}

	@RequestMapping("approval")
	public ModelAndView approval(HttpServletRequest req) {
		return this.getModelAndView();
	}

	@RequestMapping("approvalEdit")
	public ModelAndView manageEdit(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"knowledge/knowledgeItem/approvalEdit");
		KngKnowledgeItem model = null;

		// String categoryId = req.getParameter("categoryId");

		if (StringUtils.isNotEmpty(id)) {
			model = this.getService().findOne(id);
			// model.setKngKnowledgeCategoryId(categoryId);
		} else {
			model = new KngKnowledgeItem();

			model.setId(HibernateUUIDGenerator.generate());
			model.setAccessRight("companyLevel");
		}

		if (model == null) {
			mv.setViewName("");
			return mv;
		}

		if (StringUtils.isNotEmpty(model.getKngKnowledgeCategoryId())) {
			KngKnowledgeCategoryService kngKnowledgeCategoryService = ContextHolder
					.getSpringBean("kngKnowledgeCategoryService");

			KngKnowledgeCategory cat = kngKnowledgeCategoryService
					.findOne(model.getKngKnowledgeCategoryId());
			if (cat != null) {
				mv.addObject("categoryName", cat.getName());
			}
		}
		String fromId = req.getParameter("fromId");
		if (StringUtils.isNotEmpty(fromId)) {
			mv.addObject("fromId", fromId);
		}
		String fromProcessKey = req.getParameter("fromProcessKey");
		if (StringUtils.isNotEmpty(fromProcessKey)) {
			mv.addObject("fromProcessKey", fromProcessKey);
		}

		mv.addObject("model", model);

		return mv;
	}

	@RequestMapping("manageList")
	@ResponseBody
	public PageResponse<Map<String, Object>> manageList(JqGridRequest request,
			HttpServletRequest req) {
	  PageResponse<Map<String, Object>> page=this.getListDetail(createManageCountQuery(), request, req);
		return page;
	}

	// ～-------------------------end 事件监控------------------------------------
	protected CountQuery createManageCountQuery() {

		CountQuery cq = createDefaultCountQuery();

		cq.addCountFilter("已发布", true,
				" status ='发布'  AND (process_id IS NOT NULL  OR  process_id<>'' )");

		cq.addCountFilter("待发布", true,
				"  status<>'发布'  AND (process_id IS NOT NULL OR process_id<>'' ) ");
	
		cq.addCountFilter("未提交", true,
        "  (process_id IS  NULL OR process_id='')  ");
		
		cq.addCountFilter("所有", true,
        " 1=1 ");

		return cq;
	}

	@RequestMapping("manageMenu")
	@ResponseBody
	public ITreeNode[] manageMenu() {
		return this.createManageCountQuery().getTreeNodes();
	}

	/**
	 * 编辑界面
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 */
	@Override
	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = this.getModelAndView();
		KngKnowledgeItem model = null;

		if (StringUtils.isEmpty(id)) {
			model = new KngKnowledgeItem();
			model.setId(HibernateUUIDGenerator.generate());
			mv.addObject("showStep", false);
		} else {

			model = this.getService().findOne(id);

			// mv.addObject("showStep", true);
			// // 直接获取上一条及下一条
			// JqGridRequest request = new JqGridRequest();
			// request.isPageable(false);
			// request.setSelectColumns("id");
			//
			// request.setRows(1);
			//
			// request.setSort("id", Direction.ASC);
			// request.setSearchString("id>'" + id + "'");
			// List<KngKnowledgeItem> nList =
			// this.getService().findAll(request);
			//
			// request.setSearchString("id<'" + id + "'");
			// request.setSort("id", Direction.DESC);
			// List<KngKnowledgeItem> pList =
			// this.getService().findAll(request);
			//
			// if (pList != null && pList.size() > 0) {
			// mv.addObject("pid", pList.get(0).getId());
			// }
			// if (nList != null && nList.size() > 0) {
			// mv.addObject("nid", nList.get(0).getId());
			// }

			KngKnowledgeCategoryService kngKnowledgeCategoryService = ContextHolder
					.getSpringBean("kngKnowledgeCategoryService");
			KngKnowledgeCategory cat = kngKnowledgeCategoryService
					.findOne(model.getKngKnowledgeCategoryId());
			if (cat != null) {
				mv.addObject("categoryName", cat.getName());
			}

		}

		mv.addObject("model", model);
		return mv;

	}

	@RequestMapping("rebuildIndex")
	@ResponseBody
	public ResultMessage rebuildIndex(HttpServletRequest req) throws Exception {
		String rebulidAll = req.getParameter("rebulidAll");
		String rebulidKng = req.getParameter("rebulidKng");
		String rebulidIcd = req.getParameter("rebulidIcd");
		boolean delta = false;
		if (StringUtils.isEmpty(rebulidAll)) {
			delta = true;
		}
		SolrUtils.rebuildServicecatalogIndex();
		if (StringUtils.isNotEmpty(rebulidKng)) {
			SolrUtils.rebuildKnowledgeIndex(null, delta);
		}
		if (StringUtils.isNotEmpty(rebulidIcd)) {
			SolrUtils.rebuildIncidentIndex(null, delta);
		}

		return ResultMessage.success();
	}

	@RequestMapping("myKnowledgeView")
	public ModelAndView myKnowledgeView(HttpServletRequest req) {
		return this.getModelAndView();
	}

	@Override
	@RequestMapping("save")
  @ResponseBody
  public ResultMessage save(KngKnowledgeItem model, HttpServletRequest req) {

    this.getService().saveOrUpdate(model, req);
    KngKnowledgeItem entity=this.getService().findOne(model.getId());
    String stauts=entity.getStatus();
    String processId=entity.getProcessId();
    
    if(stauts!=null && processId!=null)
    {
      if(stauts.equals("发布"))
      {
        try {
          BpmProcessRunService bpmProcessRunService = ContextHolder
              .getSpringBean("bpmProcessRunService");
          bpmProcessRunService.reOpenProcess(processId);
          bpmProcessRunService.jumpto(processId, "sid-A9148777-B9F8-4982-92FF-BE7214F6AA0D", ContextHolder.getLoginUsername(),
              "");
          return ResultMessage.success("已提交审核");
        } catch (Exception ex) {
          return ResultMessage.failure(ex);
        }
      }
    }
    
    return ResultMessage.newInstance(true, null, model.getId());
  }
}
